package com.bonc.web.user;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 用户密码验证失败次数缓存实现类
 * @Author: ChenZhiXiang
 * @CreateDate: 2019/3/1 0001 16:35
 * @Version: 1.0
 */
@Component
public class UserCacheImpl implements UserCache {

    @Autowired
    private CacheManager cacheManager;

    /**
     * 根据用户账号查询账号是否还在锁定时间里
     * @param userName
     * @return
     */
    @Override
    public boolean isLock(String userName) {
        Cache cache = cacheManager.getCache("userCache");
        String username = cache.get(userName,String.class);
        if (username == null){
            return false;
        }
        return true;
    }

    /**
     * 用户登陆失败，往缓存中记录失败的次数，次数到5次，锁定账号
     * @param userName
     * @return
     */
    @Override
    public void upCount(String userName) {
        Cache cache = cacheManager.getCache("countCache");
        Integer count = cache.get(userName,Integer.class);
        if (count != null){
            if (count.intValue() >= UserConstants.USER_PASSWORD_ERROR){
                // 调用用户锁定时限的缓存
                Cache cache1 = cacheManager.getCache("userCache");
                cache1.put(userName,"密码大于2次了");
                // 移除当前用户计数
                cache.evict(userName);
            } else {
                cache.put(userName,++count);
            }
        } else {
           count = 1;
           cache.put(userName,count);
        }
    }

    @Override
    public Integer getCount(String username) {
        Cache cache = cacheManager.getCache("countCache");
        Integer count = cache.get(username,Integer.class);
        return count.intValue();
    }
}
